/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.gateway.plugin.tenant.strategy;

import com.gateway.common.constant.ContextConstants;
import com.gateway.common.dto.convert.rule.impl.TenantRuleHandle;
import com.gateway.common.enums.GatewayRetCodeEnum;
import com.gateway.plugin.tenant.exception.TenantException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class DefaultJwtConvertStrategy implements JwtConvertStrategy {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultJwtConvertStrategy.class);

    @Override
    public ServerWebExchange convert(final TenantRuleHandle tenantRuleHandle, final ServerWebExchange exchange, final Map<String, Object> jwtBody) {
        if (CollectionUtils.isEmpty(tenantRuleHandle.getConverter())) {
            return exchange;
        }

        return convert(exchange, jwtBody, tenantRuleHandle);
    }

    /**
     * The parameters in token are converted to request header.
     *
     * @param exchange exchange
     * @return ServerWebExchange exchange.
     */
    private ServerWebExchange convert(final ServerWebExchange exchange,
                                      final Map<String, Object> jwtBody, final TenantRuleHandle tenantRuleHandle) {
        ServerHttpRequest modifiedRequest = exchange.getRequest().mutate().headers(httpHeaders -> this.addHeader(httpHeaders, jwtBody, tenantRuleHandle)).build();
        return exchange.mutate().request(modifiedRequest).build();
    }

    /**
     * add header.
     *
     * @param headers    headers
     * @param body       body
     * @param ruleHandle converters
     */
    private void addHeader(final HttpHeaders headers,
                           final Map<String, Object> body,
                           final TenantRuleHandle ruleHandle) {
        List<TenantRuleHandle.Convert> converters = ruleHandle.getConverter();
        for (TenantRuleHandle.Convert converter : converters) {

            if (StringUtils.isEmpty(converter.getHeaderVal()) || StringUtils.isEmpty(converter.getJwtVal())) {
                continue;
            }

            if (converter.getJwtVal().contains(".")) {
                headers.add(converter.getHeaderVal(), parse(body, converter.getJwtVal().split("\\."), new AtomicInteger(0)));
            }
            String jwtVal = String.valueOf(body.get(converter.getJwtVal()));
            if (converter.isOnlyOneHeaderVal()) {
                List<String> headerValList = headers.getOrDefault(converter.getHeaderVal(), new ArrayList<>(1));
                for (String headerVal : headerValList) {
                    if (!StringUtils.equals(headerVal, jwtVal)) {
                        throw new TenantException(GatewayRetCodeEnum.REQUEST_HEADER_MODIFIED, converter.getHeaderVal());
                    }
                }
            } else {
                headers.add(converter.getHeaderVal(), jwtVal);
            }
        }
        headers.add(ContextConstants.CTX_KEY_TENANT_NAME, ruleHandle.getTenantName());
        headers.add(ContextConstants.CTX_KEY_APP_NAME, ruleHandle.getAppName());
    }

    /**
     * Parsing multi-level tokens.
     *
     * @param body  token
     * @param split jwt of key
     * @param deep  level default 0
     * @return token of val
     */
    private String parse(final Map<String, Object> body,
                         final String[] split,
                         final AtomicInteger deep) {
        for (Map.Entry<String, Object> entry : body.entrySet()) {

            if (deep.get() == split.length - 1) {
                return String.valueOf(body.get(split[deep.get()]));
            }

            if (entry.getKey().equals(split[deep.get()])) {
                if (entry.getValue() instanceof Map) {
                    deep.incrementAndGet();
                    return parse((Map<String, Object>) entry.getValue(), split, deep);
                }
            }
        }
        return String.valueOf(body.get(split[deep.get()]));
    }
}
